#!/usr/bin/env python3.8
# -*- encoding: utf-8 -*-
'''
@File    :   __init__.py
@Time    :   2021/10/07 16:01:49
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
import click

from flask import Flask
from configs import config  
from app.ext import bootstrap,db,login_manager,moment,migrate
from app.blueprint import todolist_bp
from app.models import User,TodoList

def create_app(config_class=config):
    app = Flask(__name__)
    app.config.from_object(config['development'])
    register_extensions(app)
    register_blueprints(app)
    register_shell_context(app)
    register_commands(app)

    if not app.debug and not app.testing:
        if not os.path.exists('logs'):
            os.mkdir('logs')
        file_handler = RotatingFileHandler('logs/myblog.log', maxBytes=10240, backupCount=10)
        file_handler.setFormatter(
            logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)

        app.logger.setLevel(logging.INFO)
        app.logger.info('todolist startup')
    return app


def register_extensions(app):
    db.init_app(app)
    login_manager.init_app(app)
    moment.init_app(app)
    migrate.init_app(app, db)
    bootstrap.init_app(app)


def register_blueprints(app):
    app.register_blueprint(todolist_bp)


def register_shell_context(app):
    @app.shell_context_processor
    def make_shell_context():
	    return {'db':db, 'User':User, 'TodoList':TodoList}


def register_commands(app):
    @app.cli.command()
    @click.option('--todolist', default=50, help='Quantity of todolist, default is 50.')
    def forge(todolist):
        """Generate fake data."""
        from app.fake import fake_user, fake_todolist

        db.drop_all()
        db.create_all()

        click.echo('Generating the administrator...')
        fake_user()

        click.echo('Generating %d todolist...' % todolist)
        fake_todolist(todolist)
